import { useState, useEffect, useContext } from 'react';
import { NavBar, Tabs, List, ActionSheet, SwipeAction, InfiniteScroll, Toast, Dialog } from 'antd-mobile';
import { MoreOutline, DeleteOutline } from 'antd-mobile-icons';
import { useHistory, useRouteMatch } from "react-router-dom";

import SingleMessage from '../../../components/SingleMessage';
import AvatarImage from '../../../components/AvatarImage';

import { MySdkStoreContext } from '../../../context';
import { resolveMsgFormContent } from '../../../utils';
import { ConversationType } from '../../../constants';

import './style.scss';

export default function() {
  const history = useHistory();
  // todo: url decode有问题
  const { params: { tagCode } } = useRouteMatch();
  const mySdkStore = useContext(MySdkStoreContext);
  const [moreOperationVisible, setMoreOperationVisible] = useState(false);
  const [messageResult, setMessageResult] = useState({ list: [], pagination: {}});
  const [conversationResult, setConversationResult] = useState({ list: [], pagination: {}});
  const [contactorResult, setContactorResult] = useState({ list: [], pagination: {}});
  const [tagName, setTagName] = useState('');

  useEffect(async () => {
    const res = await mySdkStore.sdk.queryFavoriteTags();
    const tagInfo = res.find(item => item.code === tagCode);
    if (tagInfo) {
      setTagName(tagInfo.name);
    }
  }, []);

  const TabKey = {
    Message: {
      key: 'Message',
      queryApi: 'queryFavoriteMessages',
      deleteApi: 'batchDeleteFavoriteMessages',
      list: messageResult.list,
      pagination: messageResult.pagination,
      setFunc: setMessageResult
    },
    Conversation: {
      key: 'Conversation',
      queryApi: 'queryFavoriteConversations',
      deleteApi: 'batchDeleteFavoriteConversations',
      list: conversationResult.list,
      pagination: conversationResult.pagination,
      setFunc: setConversationResult
    },
    Contactor: {
      key: 'Contactor',
      queryApi: 'queryFavoriteUsers',
      deleteApi: 'batchDeleteFavoriteUsers',
      list: contactorResult.list,
      pagination: contactorResult.pagination,
      setFunc: setContactorResult
    },
  }

  const [tabKey, setTabKey] = useState(TabKey.Message.key);

  const getList = async (pageIndex, key = tabKey ) => {
    const res = await mySdkStore.sdk[TabKey[key].queryApi]({ tagCodes: [tagCode], pageIndex, pageSize: 100 });
    // todo: 没有totalItemCount, totalPage字段
    const { list: rows, totalItemCount = 0, totalPage = 1 } = res;
    TabKey[key].setFunc({ list: pageIndex === 1 ? rows : [...TabKey[key].list, ...rows], pagination: { pageIndex, totalItemCount, totalPage }});
  }

  useEffect(() => {
    Object.keys(TabKey).forEach((key) => {
      getList(1, key);
    })
  }, []);

  const handleTabChange = (key) => {
    setTabKey(key);
    getList(1, key);
  }

  const handleDelete = async (id: string, tabKey, deleteKey, keyInList?: string) => {
    await mySdkStore.sdk[TabKey[tabKey].deleteApi]({ tagCode, [`${deleteKey}s`]: [id] });
    TabKey[tabKey].setFunc({
      list: TabKey[tabKey].list.filter(item => item[keyInList || deleteKey] !== id),
      pagination: { ...TabKey[tabKey].pagination, totalItemCount: TabKey[tabKey].pagination.totalItemCount - 1 }
    });
  }

  const handleDeleteTag = async () => {
    const isConfirm = await Dialog.confirm({
      content: '确定要删除标签吗？',
    });
    if (!isConfirm) {
      return;
    }
    try {
      await mySdkStore.sdk.deleteFavoriteTag({ tagCode });
      Toast.show('标签已删除');
      history.goBack();
    } catch (e) {
      // @ts-ignore
      Toast.show(e?.errorMessage);
    }
  }

  const actions = [
    { text: '编辑标签名称', key: 'edit', onClick: () => history.push({ pathname: `/modifyCollection/${tagCode}`}) },
    { text: '删除标签', key: 'delete', onClick: handleDeleteTag },
  ];

  return (<div className="collectionFoldPage">
    <NavBar
      onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}
      right={<MoreOutline style={{ fontSize: 20, color: 'rgba(0,0,0,.65)' }} onClick={ () => setMoreOperationVisible(true) } />}>
      {tagName}
    </NavBar>
    <Tabs onChange={handleTabChange} className="pageTab">
      <Tabs.Tab title={`消息`} key={TabKey.Message.key}>
        <List style={{ '--border-top': 0, '--border-bottom': 0, '--align-items': 'top', marginBottom: 12 }}>
          {messageResult.list.map(item =>
          <SwipeAction
            key={item.msgId}
            rightActions={[{ key: 'delete', text: <DeleteOutline />, color: '#F5222D', onClick: () => handleDelete(item.msgId, TabKey.Message.key, 'msgId', 'msgId') }]}
          >
            <List.Item
              key={item.msgId}
              prefix={
                <AvatarImage
                  src={item.from?.avatarUrl}
                  style={{ marginTop: 12, borderRadius: 8 }}
                  fit='cover'
                  width={42}
                  height={42}
                  nickName={item.from?.nickName}
                  userName={item.from?.userName}
                  userId={item.from?.userId}
                />}
            >
              <div className="userName">{item.from?.nickName}</div>
              <div className="userMessage"><SingleMessage type={item.msgType} {...item} /></div>
              {/* todo: 没有回话字段 */}
              {/* <div className="messageSource">来自会话：张三 <RightOutline /> </div> */}
            </List.Item>
          </SwipeAction>)}
        </List>
      <InfiniteScroll loadMore={() => getList(messageResult.pagination.pageIndex + 1)} hasMore={messageResult.pagination.totalPage > messageResult.pagination.pageIndex} />
      </Tabs.Tab>
      <Tabs.Tab title={`会话`} key={TabKey.Conversation.key}>
      <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
        {conversationResult.list.map(item => {
          const { lastMsgContentType, lastMsgContent } = item;
          return <SwipeAction
            key={item.cid}
            rightActions={[{ key: 'delete', text: <DeleteOutline />, color: '#F5222D', onClick: () => handleDelete(item.cid, TabKey.Conversation.key, 'cid') }]}
          >
            <List.Item
              key={item.cid}
              prefix={<AvatarImage
              src={item.sessionLogoUrl}
              style={{ borderRadius: 8 }}
              fit='cover'
              width={42}
              height={42}
              userName={item.type === ConversationType.Single ? item.sessionName : ''}
              groupName={item.type === ConversationType.Group ? item.sessionName : ''}
            />}
            description={resolveMsgFormContent(lastMsgContentType, lastMsgContent)}
          >{item.sessionName}</List.Item>
          </SwipeAction>
        })}
      </List>
      <InfiniteScroll loadMore={() => getList(conversationResult.pagination.pageIndex + 1)} hasMore={conversationResult.pagination.totalPage > conversationResult.pagination.pageIndex} />
      </Tabs.Tab>
      <Tabs.Tab title={`联系人`} key={TabKey.Contactor.key}>
      <List style={{ '--border-top': 0, '--border-bottom': 0, '--border-inner': 0 }}>
        {contactorResult.list.map(item => {
          return <SwipeAction
            key={item.userId}
            rightActions={[{ key: 'delete', text: <DeleteOutline />, color: '#F5222D', onClick: () => handleDelete(item.userId, TabKey.Contactor.key, 'userId') }]}
          >
            <List.Item
              key={item.userId}
              prefix={<AvatarImage
              src={item.avatarUrl}
              style={{ borderRadius: 8 }}
              fit='cover'
              width={42}
              height={42}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
            />}
            description={<>ID: {item.userId}</>}
          >{item.nickName}</List.Item>
          </SwipeAction>
        })}
      </List>
      <InfiniteScroll loadMore={() => getList(contactorResult.pagination.pageIndex + 1)} hasMore={contactorResult.pagination.totalPage > contactorResult.pagination.pageIndex} />
      </Tabs.Tab>
    </Tabs>
    <ActionSheet
      extra={ tagName }
      cancelText='取消'
      visible={moreOperationVisible}
      actions={actions}
      onClose={() => setMoreOperationVisible(false)}
    />
  </div>)
}